#import "XMLoginRecordView.h"
#import "XMAudioRecorder.h"
#import "SpectrumView.h"
#import <AVFoundation/AVFoundation.h>

static NSInteger const kVoiceRecordMinTime = 5;
static NSInteger const kVoiceRecordMaxTime = 30;

@interface XMLoginRecordView () <XMAudioRecorderDelegate>
@property (weak, nonatomic) IBOutlet UIView *animationBgV;
@property (weak, nonatomic) IBOutlet UILabel *timeLa;
@property (weak, nonatomic) IBOutlet UILabel *tipLa;
@property (nonatomic, assign) NSUInteger time;
@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, strong) NSTimer *timeTimer;
@property (strong, nonatomic) SpectrumView *spectrumView;
@property (nonatomic, assign) BOOL start;
@property (weak, nonatomic) IBOutlet UIView *bgV;

@end

@implementation XMLoginRecordView

- (void)awakeFromNib {
    [super awakeFromNib];
    _bgV.layer.mask = [UIView xm_viewClipRect:CGRectMake(0, 0, kScreenWidth, 310) rectCorner:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(16, 16)];
    
//    self.tipLa.text = kStringFormat(@"请录制%ld至%ld秒时长的问候语", kVoiceRecordMinTime, kVoiceRecordMaxTime);
    self.spectrumView = [[SpectrumView alloc] initWithFrame:CGRectZero];
    XMWeakSelf(self);
    self.spectrumView.itemLevelCallback = ^() {
        XMStrongSelf(self);
        if (self.start) {
            [[XMAudioRecorder.shareInstance getAVAudioRecorder] updateMeters];
            //取得第一个通道的音频，音频强度范围是-160到0
            float power = [[XMAudioRecorder.shareInstance getAVAudioRecorder] averagePowerForChannel:0];
            self.spectrumView.level = power;
        } else {
            self.spectrumView.level = -160;
        }
        
    };
    [self.animationBgV addSubview:self.spectrumView];
    [self.spectrumView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.animationBgV);
    }];
    // 开始
    [self.spectrumView.recordButton addTarget:self action:@selector(recordStart:) forControlEvents:UIControlEventTouchDown];
    // 取消
    //    [self.spectrumView.recordButton addTarget:self action:@selector(recordCancel:) forControlEvents: UIControlEventTouchUpOutside];
    // 完成
    [self.spectrumView.recordButton addTarget:self action:@selector(recordFinish:) forControlEvents:UIControlEventTouchUpInside];
    // 移出
    [self.spectrumView.recordButton addTarget:self action:@selector(recordFinish:) forControlEvents:UIControlEventTouchDragExit];
    //    //移入
    //    [self.spectrumView.recordButton addTarget:self action:@selector(recordTouchDragEnter:) forControlEvents:UIControlEventTouchDragEnter];
    
    
    //    self.filePath = [self getFilePathWithFileName:@"GreetRecord.m4a"];
    //    [[YHAudioRecorder shareInstance] startRecordWithFilePath:self.filePath];
    //    [[YHAudioRecorder shareInstance] setRecorderDelegate:self];
    //    if (_timeTimer == nil) {
    //        self.time = 0;
    //        self.timeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(recorderTimeChange) userInfo:nil repeats:YES];
    //    }
    
}

- (IBAction)close:(UIButton *)sender {
    if (self.closeBlock) {
        self.closeBlock();
    }
}

#pragma mark - ControlEvents
- (void)recordStart:(UIButton *)button {
    [self startRecord];
}

- (void)recordFinish:(UIButton *)button {
    if (self.time < kVoiceRecordMinTime) {
        [MBProgressHUD showHUDMsg:self.tipLa.text toView:nil];
    }
    [self stopRecord];
}

#pragma mark - 完成
- (IBAction)finishAct:(UIButton *)sender {
    if (self.time < kVoiceRecordMinTime) {
        [MBProgressHUD showHUDMsg:self.tipLa.text toView:nil];
        [self stopRecord];
        return;
    }
    
    if (self.time >= kVoiceRecordMinTime) {
        self.completeBlock(self.filePath, self.time);
    } else {
        if (self.closeBlock) {
            self.closeBlock();
        }
    }
}

- (void)startRecord {
    if (!XMAudioRecorder.shareInstance.isRecording) {
        NSLog(@"录音开始");
        self.filePath = [self getFilePathWithFileName:@"voice_desc.m4a"];
        [[XMAudioRecorder shareInstance] startRecordWithFilePath:self.filePath];
        [[XMAudioRecorder shareInstance] setRecorderDelegate:self];
        if (_timeTimer == nil) {
            self.time = 0;
            self.timeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(recorderTimeChange) userInfo:nil repeats:YES];
        }
        self.start = YES;
        [self.spectrumView start];
    }
}

- (void)stopRecord {
    if (XMAudioRecorder.shareInstance.isRecording) {
        self.start = NO;
        if (self.time < kVoiceRecordMinTime) {
            self.time = 0;
            self.timeLa.text = @"长按录制 松开结束";
        }
        [self stopTimer];
        [self.spectrumView stop];
        self.spectrumView.level = -160;
        [XMAudioRecorder shareInstance].isClose = YES;
        [[XMAudioRecorder shareInstance] stopRecord];
    }
}

- (void)stopTimer {
    if (self.timeTimer) {
        [self.timeTimer invalidate];
        self.timeTimer = nil;
    }
}

- (void)recorderTimeChange {
    self.time += 1;
    self.timeLa.text = kStringFormat(@"已录制%lds", self.time);
//    self.timeLa.text = [self timeTextString:self.time];
    if (self.time >= kVoiceRecordMaxTime) {
        [self recordFinish:nil];
    }
}

- (NSString *)timeTextString:(NSInteger)seconds {
    NSString *str_hour = [NSString stringWithFormat:@"%02ld", seconds / 3600 % 24];
    NSString *str_minute = [NSString stringWithFormat:@"%02ld", (seconds % 3600) / 60];
    NSString *str_second = [NSString stringWithFormat:@"%02ld", seconds % 60];
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@", str_hour, str_minute, str_second];
    return format_time;
}

#pragma mark - YHAudioRecorderDelegate
- (void)audioRecorderDidVoiceChanged:(XMAudioRecorder *)recorder value:(double)value {
}
- (void)audioRecorderDidFinished:(XMAudioRecorder *)recorder successfully:(BOOL)flag {
    if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath] && flag) {
        if (self.completeBlock) {
            self.completeBlock(self.filePath, self.time);
        }
    }
}
- (NSString *)getFilePathWithFileName:(NSString *)fileName {
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    filePath = [filePath stringByAppendingPathComponent:fileName];
    return filePath;
}
- (void)dealloc {
    [self stopTimer];
}

//- (IBAction)start:(UIButton *)sender {
//    self.filePath = [self getFilePathWithFileName:@"LoginRecord.m4a"];
//    [[YHAudioRecorder shareInstance] startRecordWithFilePath:self.filePath];
//    [[YHAudioRecorder shareInstance] setRecorderDelegate:self];
//    self.start = YES;
//    if (_timeTimer == nil) {
//        self.time = 0;
//        self.timeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(recorderTimeChange) userInfo:nil repeats:YES];
//    }
//}
//
//
//- (IBAction)closeAction:(UIButton *)sender {
//    [self stopTimer];
//    [YHAudioRecorder shareInstance].isClose = YES;
//    [[YHAudioRecorder shareInstance] stopRecord];
//    if (self.closeBlock) {
//        self.closeBlock();
//    }
//}
//
//- (IBAction)paseAction:(UIButton *)sender {
//    sender.selected = !sender.selected;
//    if (sender.selected) {
//        self.timeTimer.fireDate = [NSDate distantFuture];
//        [[YHAudioRecorder shareInstance] pauseRecord];
//    } else {
//        self.timeTimer.fireDate = [NSDate distantPast];
//        [[YHAudioRecorder shareInstance] resumeRecord];
//    }
//}
//
//- (void)completeAction {
//    if (self.time <= kVoiceRecordMinTime) {
//        [MBProgressHUD showHUDMsg:self.tipLa.text toView:nil];
//        return;
//    }
//    [self stopTimer];
//    [YHAudioRecorder shareInstance].isClose = NO;
//    [[YHAudioRecorder shareInstance] stopRecord];
//}

//
//- (void)recordCancel:(UIButton *)button {
//    if (YHAudioRecorder.shareInstance.isRecording) {
//        NSLog(@"取消");
//        self.start = NO;
//        [self stopTimer];
//        [YHAudioRecorder shareInstance].isClose = YES;
//        [[YHAudioRecorder shareInstance] stopRecord];
//
//    }
//}

//- (void)recordTouchDragExit:(UIButton *)button {
//    if([self.audioRecorder isRecording]) {
//        self.tipLabel.text = @"松开取消";
//        [self stopAnimate];
//    }
//}
//
//- (void)recordTouchDragEnter:(UIButton *)button {
//    if([self.audioRecorder isRecording]) {
//        self.tipLabel.text = @"正在录音";
//        [self startAnimate];
//    }
//}

@end
